package com.jbookshelf.dal.providers;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jbookshelf.dal.entities.Authors;

@Repository
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public class AuthorsDataProviderImpl implements AuthorsDataProvider {

	@Autowired
	SessionFactory sessionFactory;

	@Override
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public List<Authors> getAuthors() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from Authors a");
		return query.list();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void addAuthor(String fullName, String email, Date birthDay) {
		Session session = sessionFactory.getCurrentSession();
		Authors author = new Authors(fullName);
		author.setEmail(email);
		author.setBirthday(birthDay);
		session.save(author);
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public boolean checkFullName(String fullName) {
       Query query = sessionFactory.getCurrentSession().
    		   createQuery("from Authors where fullName=:name");
      if ( query.setString("name", fullName.trim()).uniqueResult()==null){
    	  return true;
      } else
      {
		return false;
      }
	}

}
